<template>
  <div>
    <div v-for="(item, index) in list" :key="index">
      <batch-form
        :fields="fields"
        :column-num="columnNum"
        :index="index"
        ref="batchForm"
        :list="list"
        :item="item"
        :cerat-form="ceratForm"
        :task-from="taskFrom"
        @add="add"
        @del="del"
        @receipt='receipt'
      />
    </div>
  </div>
</template>

<script>
import { t } from '@src/locales';
import {
  FormFieldMap,
  SettingComponents,
} from '@src/component/form/components';
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import * as CustomerApi from '@src/api/CustomerApi.ts';

/* utils */
import _ from 'lodash';
import * as Utils from '@src/component/form/util';

import { formatDate } from 'pub-bbx-utils';

import SearchProductSelect from './SearchProductSelect.vue';
import SearchCustomerSelect from './SearchCustomerSelect.vue';
// 操作符
const OperatorSelectOptionsMap = {
  input: [
    { label: t('common.base.include'), value: 'like' },
    { label: t('common.base.equal'), value: 'eq' },
    { label: t('common.base.greaterThan'), value: 'gt' },
    { label: t('common.base.greaterThanOrEqual'), value: 'ge' },
    { label: t('common.base.lessThan'), value: 'lt' },
    { label: t('common.base.lessThanOrEqual'), value: 'le' },
  ],
  text: [
    { label: t('common.base.include'), value: 'like' },
    { label: t('common.base.equal'), value: 'eq' },
  ],
  multiple: [
    { label: t('common.base.include'), value: 'in'},
    { label: t('common.base.exclude'), value: 'not_in' },
  ],
  description: [
    { label: t('common.base.include'), value: 'like' },
  ],
  date: [{ label: t('common.base.between'), value: 'between' }],
  select: [{ label: t('common.base.equal'), value: 'eq' }],
  cascader: [
    { label: t('common.base.include'), value: 'cascader' },
    { label: t('common.base.exclude'), value: 'not_in' },
  ],
  many: [
    { label: t('common.base.include'), value: 'in' },
    { label: t('common.base.exclude'), value: 'not_in' },
  ],
};

// 多选类型
const MultiFieldNames = [
  'serviceType',
  'serviceContent',
  'level',
  'paymentMethod',
  'state',
  'allotTypeStr',
  'onceException',
  'allotUser',
  'tags',
  'synergyId',
  'createUser',
  'executor',
];

// 根据类型判断属于哪个操作符
function setFieldOperateHandler(field = {}) {
  let { fieldName, formType, setting } = field;

  if (formType == 'number') {
    field.operatorOptions = OperatorSelectOptionsMap.input.slice();
  } else if (MultiFieldNames.indexOf(fieldName) > -1) {
    field.operatorOptions = OperatorSelectOptionsMap.multiple.slice();
  } else if (fieldName == 'customer' || fieldName == 'product') {
    field.operatorOptions = OperatorSelectOptionsMap.select.slice();
  } else if (formType === 'description' || fieldName === 'eventNo') {
    field.operatorOptions = OperatorSelectOptionsMap.description.slice();
  } else if (
    formType == 'text'
    || formType == 'textarea'
    || formType === 'code'
    || formType === 'relationProduct'
    || formType === 'relationCustomer'
  ) {
    field.operatorOptions = OperatorSelectOptionsMap.text.slice();
  } else if (formType == 'date' || formType == 'datetime' || formType === 'planTime'|| formType === 'planStartTime'|| formType === 'planEndTime') {
    field.operatorOptions = OperatorSelectOptionsMap.date.slice();
  } else if (formType == 'select' && !setting.isMulti) {
    field.operatorOptions = OperatorSelectOptionsMap.select.slice();
  } else if (formType == 'select' && setting.isMulti) {
    field.operatorOptions = OperatorSelectOptionsMap.many.slice();
  } else if (formType === 'cascader') {
    field.operatorOptions = OperatorSelectOptionsMap.cascader.slice();
  } else {
    field.operatorOptions = OperatorSelectOptionsMap.select.slice();
  }

  field.operatorValue = field.operatorOptions[0].value;
}

export default {
  name: 'task-inquire',
  props: {
    columnNum: {
      type: Number, // 一栏二栏
      default: 1,
    },
    searchList: {
      type: Array, // 搜索数据
      default: () => {[]}
    },
    taskFrom: {
      type: Object | String
    }, // 初始值
  },
  data() {
    return {
      list: [], // 自定义列表
      ceratForm: {},
      params: {}
    };
  },
  watch: {
    searchList(v) {
      this.fields
      this.list = []
      if (this.taskFrom && Object.keys(this.taskFrom).length) {
        v.forEach(item => {
          for(let key in this.taskFrom) {
            if (key === item.fieldName) {
              this.list.push({...item, searchValue: this.taskFrom[key]})
            }
          }
        })
      } else {
        this.list = [v[0]]
      }
    },
    taskFrom(v) {
      if (!v) this.list = [this.searchList[0]].map(item => { item.searchValue = '';return item})
    }
  },
  computed: {
    //  搜索数据转换
    fields() {
      let f = {};
      let fields = this.searchList.map((field) => {
        f = _.cloneDeep(field);

        let formType = f.formType;

        if (formType === 'datetime' || formType === 'planTime'|| formType === 'planStartTime'|| formType === 'planEndTime') {
          formType = 'date';
        }

        if (formType === 'updateTime') {
          f.displayName = this.$t('task.list.displayName.updateTime');
        }

        setFieldOperateHandler(f);

        return {
          ...f,
          isNull: 1,
          formType,
          originalFormType: f.formType,
          operator: this.matchOperator(f),
        };
      });
      return fields;
    },
  },
  methods: {
    // 搜索选中的值
    returnData() {
      let data = {}, dataList = [], dataView = {}
      if (!this.$refs.batchForm) return {};
      this.$refs.batchForm.forEach((item) => {
        for (let key in item.returnDatas()) {
          const value = item.returnDatas()[key];
          if (value && JSON.stringify(value) !== '[]' && JSON.stringify(value) !== '{}') {
            data[key] = value
            dataList.push({key, value})
          }
        }
      });

      // 回执所需要的内容
      dataList.map(item => {
        for(let key in this.params) {
          if (item.key === key) {
            item.value = this.params[key]
          }
        }
        return item
      }).forEach(item => {
        if (item.key === 'datetime' || item.key === 'planTime'|| item.key === 'planStartTime'|| item.key === 'planEndTime') {
          dataView[item.key] = item.value.map(v => {return formatDate(v, 'YYYY-MM-DD')})
        } else {
          dataView[item.key] = item.value
        }
      })

      return {data, dataView};
    },
    // 回执内容 不为文案
    receipt(v) {
      for(let key in v) {
        this.params[key] = v[key]
      }
    },

    // 初始化操作符
    matchOperator(field) {
      let formType = field.formType;
      let operator = '';

      switch (formType) {
      case 'date': {
        operator = 'between';
        break;
      }
      case 'datetime': {
        operator = 'between';
        break;
      }
      case 'select': {
        if (field.setting && field.setting.isMulti) {
          operator = 'contain';
        } else {
          operator = 'eq';
        }
        break;
      }
      case 'user': {
        operator = 'user';
        break;
      }
      case 'address': {
        operator = 'address';
        break;
      }
      case 'cascader': {
        operator = 'cascader';
        break;
      }
      case 'location': {
        operator = 'location';
        break;
      }
      default: {
        operator = 'like';
        break;
      }
      }
      return operator;
    },
    // 添加
    add() {
      // 清除已选择的类型
      let searchSet = []
      this.fields.forEach(item => {
        let condition = this.list.some(v => {
          return v.fieldName === item.fieldName
        })
        if (!condition) {
          searchSet.push(item) 
        }
        if (this.list.length >= this.fields.length) {
          searchSet.push(this.fields[0]) 
        }
      })
      this.list = [...this.list, ...[searchSet[0]]]
    },
    // 删除
    del({ index}) {
      this.list = this.list.map((item, i) => {
        if (i === index) {
          item = {}
        }
        return item
      })
    }
  },
  components: {
    BatchForm: {
      name: 'batch-form',
      props: {
        fields: {
          type: Array, // 搜索数据
          default: () => [],
        },
        index: {
          type: Number, // 索引
          default: 0,
        },
        columnNum: {
          type: Number, // 一栏二栏
          default: 1,
        },
        item: {
          type: Object, // item
          default: () => ({})
        },
        list: {
          type: Array, // 重新渲染
          default: () => {[]}
        },
        taskFrom: {
          type: Object | String
        }, // 初始值
      },
      data: () => {
        return {
          selectedField: {}, // 选中的条件类型
          customer: {},
          form: {}, // 初始化值
          product: {},
          userList: [],
          receipt: {}, // 回执的内容 用户 联系人
          userIds: [], // fromtype为user的
        };
      },
      watch: {
        fields() {
          if (!this.taskFrom) {
            this.selectedField = {}
            this.customer = {}
            this.form = {}
            this.userList = []
            this.product = {}
            this.receipt = {}
            this.userIds = []
          }
        }      
      },
      mounted() {
        this.reset()
      },
      methods: {
        // 初始化
        reset() {
          if (!Object.keys(this.item).length) return
          
          if (this.item.searchValue) {
            this.selectField(this.item.fieldName) 
            if (this.item.fieldName === 'customer') {
              this.customer['name'] = this.item.searchValue[0].label
              this.form[this.item.fieldName] = this.item.searchValue[0].value
            } else if (this.item.fieldName === 'product') {
              this.product['name'] = this.item.searchValue[0].label
              this.form[this.item.fieldName] = this.item.searchValue[0].value
            } else {
              this.form[this.item.fieldName] = this.item.searchValue
            }
          }
        },
        // 搜索选中的值
        returnDatas() {
          // 判断是否存在这个类型
          for(let key in this.form) {
            if (!Object.keys(this.item).length) {
              this.form[key] = ''
            }
          }
          let data = Object.assign({}, this.form);
          this.$emit('receipt', this.receipt)
          return data;
        },
        // 默认值初始化为对象
        buildForm() {
          this.fields.forEach((f) => {
            if (!this.form[f.fieldName] || !this.form[f.fieldName].length) {
              let tv = '';
              if (f.formType == 'customerAddress' || f.formType == 'address')
                tv = {};
              if (f.formType == 'date' || f.formType == 'datetime') tv = [];
              if (f.formType === 'link') {
                tv = {};
              }
              if (f.fieldName === 'tags') {
                tv = [];
              }
              if (f.formType === 'area' || f.formType === 'cascader') {
                tv = [];
              }

              if (f.formType === 'user') {
                tv = [];
              }
              if (MultiFieldNames.indexOf(f.fieldName) > -1) {
                this.form[f.fieldName] = [];
              }
              this.form[f.fieldName] = tv;
            }
          });
        },

        // 客户内容渲染
        searchCustomer(params) {
          const pms = params || {};

          return CustomerApi.getCustomerListAsyn(pms)
            .then((res) => {
              if (!res || !res.list) return;

              res.list = res.list.map((custoner) =>
                Object.freeze({
                  label: custoner.name,
                  value: custoner.id,
                  ...custoner,
                })
              );
              return res;
            })
            .catch((e) => console.error(e));
        },

        // 产品内容渲染
        searchProduct(params) {
          const pms = params || {};

          pms.customerId = this.form.customer || '';
          return TaskApi.getTaskCustonerProductList(pms)
            .then((res) => {
              if (!res.result || !res.result?.list) return;
              res.result.list = res.result.list.map((product) =>
                Object.freeze({
                  label: product.name,
                  value: product.id,
                  ...product,
                })
              );
              return res.result;
            })
            .catch((e) => console.error(e));
        },

        // 筛选框选择值
        update(event, action) {
          this.form = {};
          const f = event.field;
          if (action === 'tags') {
            return (this.form.tags = event.map(item => {return item}));
          }

          if (action === 'dist') {
            return (this.form.area = event);
          }
          
          if (f.formType === 'user') {
            let users = []
            this.userIds = [...this.userIds, ...event.options]
            let option = [...new Set(this.userIds.map(item => {
              return item = JSON.stringify(item)
            }))].map(item => {
              return item = JSON.parse(item)
            })
            option.forEach(item => {
              event.newValue.forEach(v => {
                if (v === item.id) {
                  users.push(item.name)
                }
              })
            })
            this.receipt[f.fieldName] = users
          }

          if (f.fieldName === 'tlmName') {
            let users;
            event.options.forEach(item => {
              if (event.newValue === item.id) {
                users = item.name
              }
            })
            this.receipt['tlmName'] = users
          }

          this.form[f.fieldName] = event.newValue;
        },

        // 选择筛选条件类型
        selectField(val) {
          if (!this.fields.length) return
          this.selectedField = this.fields.filter(
            (f) => f.fieldName === val
          )[0];

          this.buildForm()

          if (MultiFieldNames.indexOf(this.selectedField.fieldName) > -1) {
            this.form[val] = [];
          }
        },

        // 筛选条件内容
        renderSelector() {
          if (!this.fields) return null;

          return (
            <el-select
              value={this.selectedField.fieldName}
              onChange={this.selectField}
              filterable
            >
              {this.fields.map((f) => (
                <el-option
                  key={f.fieldName}
                  label={f.displayName}
                  value={f.fieldName}
                ></el-option>
              ))}
            </el-select>
          );
        },

        // 操作符内容
        renderOperateSelect() {
          if (!this.selectedField.operatorOptions) return;

          return (
            <el-select
              class={
                this.columnNum === 2
                  ? 'task-inquire-operator-select task-type'
                  : 'task-mt12 task-type'
              }
              value={this.selectedField.operatorValue}
              onInput={(value) => (this.selectedField.operatorValue = value)}
            >
              {this.selectedField.operatorOptions.map((operatorItem) => (
                <el-option
                  key={operatorItem.value}
                  label={operatorItem.label}
                  value={operatorItem.value}
                ></el-option>
              ))}
            </el-select>
          );
        },

        // 筛选值内容
        renderInput(h) {
          const f = this.selectedField;
          const comp = FormFieldMap.get(f.formType);
          if (!comp || f.formType === 'area') {
            return null;
          }

          if (MultiFieldNames.indexOf(this.selectedField.fieldName) > -1) {
            f.setting.isMulti = true;
          }

          if (f.formType === 'select' && !f.isSystem) {
            f.setting.isMulti = false;
          }

          let childComp = null;

          if (f.fieldName == 'customer') {
            let value = this.form[f.fieldName];
            childComp = h('search-customer-select', {
              props: {
                placeholder: this.$t('common.placeholder.selectCustomer'),
                field: f,
                value: value
                  ? [{ label: this.customer.name || '', value }]
                  : [],
                remoteMethod: this.searchCustomer,
              },
              on: {
                input: (event) => {
                  this.form = {};
                  this.customer = event && event.length > 0 ? event[0] : {};
                  this.form[f.fieldName] = this.customer.id;
                  this.receipt[f.fieldName] = [{ label: this.customer.name, value: this.customer.id }]
                },
              },
            });
          } else if (f.fieldName == 'product') {
            let value = this.form[f.fieldName];
            childComp = h('search-product-select', {
              props: {
                placeholder: this.$t('common.placeholder.selectProduct'),
                field: f,
                value: value ? [{ label: this.product.name || '', value }] : [],
                remoteMethod: this.searchProduct,
              },
              on: {
                input: (event) => {
                  this.form = {};
                  this.product = event && event.length > 0 ? event[0] : {};
                  this.form[f.fieldName] = this.product.id;
                  this.receipt[f.fieldName] = [{label: this.product.name, value: this.product.id}]
                },
              },
            });
          } else if (f.formType === 'user') {
            childComp = h('user-search', {
              props: {
                multiple: true,
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
                userList: this.userList
              },
              on: {
                update: (event) => this.update(event),
                input: (event) => {
                  if (event && event.length > 1) {
                    this.$set(this, 'product', event[0]);
                  }
                  // this.form[f.fieldName] = event.keyword;
                },
              },
            });
          } else if (f.fieldName === 'tags') {
            let value = this.form[f.fieldName];
            childComp = h('biz-team-select', {
              props: {
                multiple: true,
                value: value ? value : [],
              },
              on: {
                input: (event) => this.update(event, 'tags'),
              },
            });
          } else if (f.fieldName === 'tlmName') {
            childComp = h('linkman-search', {
              props: {
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
                userList: this.userList
              },
              on: {
                update: (event) => this.update(event),
              },
            });
          } else {
            

            let propsObj = {
              field: f,
              value: this.form[f.fieldName],
              disableMap: true,
              placeholder: Utils.genPlaceholder(f),
              seo: true,
              toggle: true,
            }
            if(f.formType === "address"){
              propsObj.showDefaultCountry = false
            }
            childComp = h(
              comp.extend && comp.extend[`${f.formType}_search`]
                ? comp.extend[`${f.formType}_search`]
                : comp.build,
              {
                props: propsObj,
                on: {
                  update: (event) => this.update(event),
                },
              }
            );
          }
          return h(
            'form-item',
            {
              props: {
                label: f.displayName,
                needValidate: false,
              },
            },
            [childComp]
          );
        },
      },
      render(h) {
        return (
          <div>
            { Object.keys(this.item).length ? (
              <div class='task-flex task-ai task-mt12 bt'>
                <div
                  class={
                    this.columnNum === 2
                      ? 'task-inquire-operator-select task-type'
                      : 'task-mt12 task-type'
                  }
                >
                  {this.renderSelector()}
                </div>

                {this.renderOperateSelect()}

                <div
                  class={
                    this.columnNum === 2
                      ? 'task-inquire-two task-flex task-ai'
                      : 'task-inquire task-flex task-ai'
                  }
                >
                  {this.renderInput(h)}
                  {this.list && this.list.length - 1 === this.index ? (
                    <div
                      class={ 'task-font14 task-c13 task-inquire-add task-ml15 task-pointer'}
                      onClick={() => {
                        this.$emit('add');
                      }}
                    >
                      {this.$t('common.base.add2')}
                    </div>
                  ) : (
                    <i
                      class="iconfont icon-shanchu1 task-pointer task-ml15 task-icon"
                      onClick={() => {
                        this.$emit('del', {index: this.index});
                      }}
                    ></i>
                  )}
                </div>
              </div>
            ) : null}
          </div>
        );
      },
      components: {
        ...SettingComponents,
        [SearchProductSelect.name]: SearchProductSelect,
        [SearchCustomerSelect.name]: SearchCustomerSelect,
      },
    },
  },
};
</script>

<style lang="scss">
.task-type {
  width: 210px !important;
  .el-select {
    width: 100%;
  }
}
.task-inquire,
.task-inquire-two {
  margin-top: 12px;
  label {
    display: none !important;
  }
  .form-item {
    width: 210px;
  }
  .form-item-control {
    width: 210px;
    flex: inherit;
    .err-msg-wrap {
      min-height: 0 !important;
      padding-bottom: 0 !important;
    }
  }
}
.task-inquire-add {
  width: 68px;
  height: 32px;
  background-color: $color-primary-light-1;
  border-radius: 4px;
  border: 1px solid $color-primary-light-2;
  text-align: center;
  line-height: 32px;
}
.task-inquire-two {
  margin: 0;
  margin-left: 12px;
}
.batch-editing-customer-dialog {
  .base-modal-body {
    padding: 10px 30px 0;
  }

  .item {
    display: flex;
    justify-content: space-between;
    line-height: 32px;
    div {
      flex-grow: 1;
      .el-select {
        width: 100%;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}

.task-inquire-operator-select {
  margin-left: 12px;
}
.bt {
  border-bottom: 1px solid #eee;
  padding-bottom: 12px;
  margin-bottom: 12px;
}
</style>
